package cn.eva.service.Impl.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.eva.common.LayuiTableResult;
import cn.eva.common.ResultJosn;
import cn.eva.dao.SysRoleMapper;
import cn.eva.dao.SysRoleMenuMapper;
import cn.eva.dao.SysUserRoleMapper;
import cn.eva.dto.SysRoleAdd;
import cn.eva.dto.SysRoleSelect;
import cn.eva.entity.SysRole;
import cn.eva.entity.SysRoleMenuKey;
import cn.eva.example.SysRoleExample;
import cn.eva.example.SysRoleExample.Criteria;
import cn.eva.example.SysRoleMenuExample;
import cn.eva.example.SysUserRoleExample;
import cn.eva.service.admin.SysRoleService;

@Service
public class SysRoleServiceImpl implements SysRoleService {
    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * 添加角色
     * 
     * @param role
     * @return
     */
    @Override
    @Transactional
    public ResultJosn add(SysRoleAdd role_add) {
        if (null != this.checkRoleName(role_add.getrName())) {
            throw new IllegalArgumentException(role_add.getrName() + "已存在");
        }
        SysRole role = (SysRole) role_add;
        role.setCreateTime(new Date());
        roleMapper.insert(role);
        // 保存角色权限
        List<Long> permissionIds = role_add.getPermissionIds();
        this.saveRolePer(role, permissionIds);
        return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), role);
    }

    /**
     * 删除角色（同时去除角色的权限、取消该角色用户的）
     */
    @Override
    @Transactional
    public ResultJosn delete(List<Long> ids) {
        this.deleteRoleMenu(ids);
        this.deleteRoleUser(ids);
        this.deleteRole(ids);
        return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), null);
    }

    /**
     * 修改角色根据id
     */
    @Override
    @Transactional
    public ResultJosn update(SysRoleAdd role_add) {
        SysRole check = this.checkRoleName(role_add.getrName());
        if (null != check && !check.getrName().equals(role_add.getrName())) {
            throw new IllegalArgumentException(role_add.getrName() + "已存在");
        }

        SysRole role = (SysRole) role_add;
        roleMapper.updateByPrimaryKeySelective(role);
        List<Long> permissionIds = role_add.getPermissionIds();
        // 修改权限
        this.saveRolePer(role, permissionIds);
        return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), role);
    }

    /**
     * 模糊查询
     */
    @Override
    public LayuiTableResult select(SysRole role, Integer page, Integer pageSize) {
        LayuiTableResult result = new LayuiTableResult();
        // 构造条件
        SysRoleExample example = new SysRoleExample();
        example.setOrderByClause("create_time DESC");
        Criteria criteria = example.createCriteria();
        if (null != role.getrId()) {
            criteria.andRIdEqualTo(role.getrId());
        } else {
            if (StringUtils.isNotBlank(role.getrName())) {
                criteria.andRNameLike("%" + role.getrName() + "%");
            }
            if (StringUtils.isNotBlank(role.getrDescription())) {
                criteria.andRDescriptionLike("%" + role.getrDescription() + "%");
            }
        }

        PageHelper.startPage(page, pageSize);
        List<SysRole> list = roleMapper.selectByExample(example);
        PageInfo<SysRole> pageInfo = new PageInfo<>(list, pageSize);
        //
        result.setCode(HttpStatus.OK.value());
        result.setMessage(HttpStatus.OK.getReasonPhrase());
        result.setCount(pageInfo.getTotal());
        result.setData(pageInfo.getList());
        return result;
    }

    /**
     * 根据id查找角色、包括角色权限列表
     */
    @Override
    public ResultJosn selectByid(Long id) {
        /*
         * 在阿里巴巴开发规范中，单操作两张表的时候应该建立索引； 这里是做链接查询，后期再看
         */
        if (null == id) {
            throw new IllegalArgumentException("id错误");
        }
        SysRoleSelect result = roleMapper.selectByid(id);
        return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), result);
    }

    /**
     * 保存角色的权限
     */
    private void saveRolePer(SysRole role, List<Long> permissionIds) {
        //
        SysRole role2 = checkRoleName(role.getrName());

        // 先删除
        if (null != role2.getrId()) {
            List<Long> rids = new ArrayList<>();
            rids.add(role2.getrId());
            deleteRoleMenu(rids);
        }
        Long rid = role2.getrId();
        // 再添加
        List<SysRoleMenuKey> list = new ArrayList<SysRoleMenuKey>();
        for (Long mid : permissionIds) {
            SysRoleMenuKey key = new SysRoleMenuKey();
            key.setRoleId(rid);
            key.setMenuId(mid);
            list.add(key);
        }
        roleMenuMapper.insertBatch(list);
    }

    /**
     * 根据name查找role
     * 
     * @return
     */
    public SysRole checkRoleName(String name) {
        SysRoleExample example = new SysRoleExample();
        Criteria criteria = example.createCriteria();
        criteria.andRNameEqualTo(name);
        List<SysRole> list = roleMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return (SysRole) list.get(0);
    }

    /**
     * 删除角色对应的权限
     */
    public void deleteRoleMenu(List<Long> rids) {
        SysRoleMenuExample example = new SysRoleMenuExample();
        example.createCriteria().andRoleIdIn(rids);
        roleMenuMapper.deleteByExample(example);
    }

    /**
     * 删除用户对应的角色
     */
    public void deleteRoleUser(List<Long> rids) {
        SysUserRoleExample example = new SysUserRoleExample();
        example.createCriteria().andRoleIdIn(rids);
        userRoleMapper.deleteByExample(example);
    }

    /**
     * 删除角色
     */
    public void deleteRole(List<Long> rids) {
        SysRoleExample example = new SysRoleExample();
        example.createCriteria().andRIdIn(rids);
        roleMapper.deleteByExample(example);
    }
}
